package me.zhengjie.modules.workorder.service.impl;

import me.zhengjie.modules.equipment.domain.TEquipment;
import me.zhengjie.modules.equipment.repository.TEquipmentRepository;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.system.common.EnumAccidentSource;
import me.zhengjie.modules.system.common.EnumWorkorderSource;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.workorder.domain.TAccident;
import me.zhengjie.modules.workorder.domain.TWorkOrder;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.workorder.repository.TAccidentRepository;
import me.zhengjie.modules.workorder.repository.TWorkOrderRepository;
import me.zhengjie.modules.workorder.service.TAccidentService;
import me.zhengjie.modules.workorder.service.TWorkOrderService;
import me.zhengjie.modules.workorder.service.dto.TAccidentDTO;
import me.zhengjie.modules.workorder.service.dto.TAccidentQueryCriteria;
import me.zhengjie.modules.workorder.service.mapper.TAccidentMapper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.collection.CollectionUtil;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

/**
* @author zcw
* @date 2019-08-10
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TAccidentServiceImpl implements TAccidentService {

    @Autowired
    private TAccidentRepository tAccidentRepository;

    @Autowired
    private TAccidentMapper tAccidentMapper;
    
    @Autowired
    private TWorkOrderService tWorkOrderService;
    
    @Autowired
    private TWorkOrderRepository tWorkOrderRepository;
    
    @Autowired
    private TEquipmentRepository tEquipmentRepository;

    @SuppressWarnings("unchecked")
	@Override
    public Object queryAll(TAccidentQueryCriteria criteria, Pageable pageable){
        Page<TAccident> page = tAccidentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<TAccidentDTO> pageDto = page.map(tAccidentMapper::toDto);
        List<TAccidentDTO> dtos = pageDto.getContent();
        if(CollectionUtil.isNotEmpty(dtos)) {
        	List<String> tEquipmentNames = null;
        	List<Integer> ids = null;
        	for(TAccidentDTO dto:dtos) {
        		String deviceIds = dto.getFaultDevice();
        		if(StringUtils.isNotEmpty(deviceIds)) {
        			String[] strs = StringUtils.split(deviceIds, ",");
        			ids = new ArrayList<Integer>();
        			for(String str:strs) {
        				ids.add(Integer.valueOf(str));
        			}
        			List<TEquipment> tEquipments = tEquipmentRepository.findAllById(ids);
        			if(CollectionUtil.isNotEmpty(tEquipments)) {
        				tEquipmentNames = new ArrayList<>();
        				for(TEquipment equipment:tEquipments) {
        					tEquipmentNames.add(equipment.getEqptname());
        				}
        			}
        			dto.setFaultDeviceNames(StringUtils.join(tEquipmentNames, ","));
        		}
        		List<TWorkOrder> orders = tWorkOrderRepository.findOrderByOrderSource(1,dto.getId());
        		if(CollectionUtil.isNotEmpty(orders)) {
                    TWorkOrder order = orders.get(0);
                    if(order.getAddriveTime() == null && dto.getReqiureTime() != null ) {  //如果预约时间为空,已故障单的时间填入,用于展示
                        order.setAddriveTime(new Timestamp(dto.getReqiureTime().getTime()));
                    }
                    dto.setOrder(order);
        		}
        	}
        }
        return PageUtil.toPage(pageDto);
    }
    
    public static void main(String[] args) {
		System.out.println(Integer.valueOf("1000000"));
	}

    @SuppressWarnings("unchecked")
	@Override
    public Object queryAll(TAccidentQueryCriteria criteria){
        return tAccidentMapper.toDto(tAccidentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TAccidentDTO findById(Long id) {
        Optional<TAccident> tAccident = tAccidentRepository.findById(id);
        ValidationUtil.isNull(tAccident,"TAccident","id",id);
        return tAccidentMapper.toDto(tAccident.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TAccidentDTO create(TAccident resources) {
        if(StringUtils.isEmpty(resources.getInputOperator())) {
            resources.setInputOperator(SecurityUtils.getName());
        }
    	resources.setInputTime(new Date());
        resources.setState(EnumWorkorderStatus.CREATED.getValue());

    	TAccidentDTO tAccidentDTO = tAccidentMapper.toDto(tAccidentRepository.save(resources));
    	TWorkOrder order = new TWorkOrder();
    	order.setSourceId(tAccidentDTO.getId());
        order.setCustomerId(resources.getCustomerId()); //客户标识
    	order.setOrderSource(EnumWorkorderSource.ENUM_WORKORDER_SOURCE_ACCIDENT.getValue()); //故障单
    	tWorkOrderService.create(order);
        return tAccidentDTO;
    }

    @Override
    public TAccidentDTO createBySupplier(TAccident resources,TServiceproviderPerson supplier) {
        resources.setInputTime(new Date());
        resources.setState(EnumWorkorderStatus.CREATED.getValue()); //已分配 TODO
        TAccidentDTO tAccidentDTO = tAccidentMapper.toDto(tAccidentRepository.save(resources));

        TWorkOrder order = new TWorkOrder();
        order.setSourceId(tAccidentDTO.getId());
        order.setOrderSource(1);
        order.setSupplier(supplier.getId());
        order.setStatus(EnumWorkorderStatus.CREATED.getValue()); //已分配 //TODO
        tWorkOrderService.create(order);

        return tAccidentDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TAccident resources) {
        Optional<TAccident> optionalTAccident = tAccidentRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTAccident,"TAccident","id",resources.getId());

        TAccident tAccident = optionalTAccident.get();
        // 此处需自己修改 TODO@@@@@ 工单修改,主要是客户供应商等的修改
        resources.setId(tAccident.getId());
        tAccidentRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        tAccidentRepository.deleteById(id);
    }

	@Override
	public Object queryAllWithOrder(TAccidentQueryCriteria criteria) {
		return tAccidentMapper.toDto(tAccidentRepository.findTAccidentWithOrder());
	}
}